package com.bz.xtcx.manager.controller;

import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.CmsExchanges;
import com.bz.xtcx.manager.entity.CmsFile;
import com.bz.xtcx.manager.service.ICmsExchangesService;
import com.bz.xtcx.manager.service.ICmsFileService;
import com.bz.xtcx.manager.utils.MyFileUtil;
import com.bz.xtcx.manager.utils.WzStrUtil;
import com.bz.xtcx.manager.vo.VoQueryExchanges;
import com.bz.xtcx.manager.vo.VoResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("exchanges")
public class ExchangesController {
    
    @Autowired
    private ICmsExchangesService cmsExchangesService;
    
    @Autowired
    private ICmsFileService cmsFileService;
    
    @Value("${file.tomcatPath}")
    private String tomcatPath;

    @PostMapping("page")
    public VoResponse getAllExchanges(@RequestBody(required=false) VoQueryExchanges query, @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoResponse voRes = new VoResponse();
        try {
            voRes.setData(cmsExchangesService.getPageByCondition(query, pageNum, pageSize, orderBy));
        } catch (XtcxException e) {
            voRes.setFail(voRes);
            voRes.setMessage("查询活动错误:" + e.getMessage());
        } catch (Exception e) {
            voRes.setFail(voRes);
            voRes.setMessage("查询活动时发生系统错误:" + e.getMessage());
        }
        return voRes;
    }
    
    @GetMapping
    public VoResponse get(@RequestParam("id") String id) {
        VoResponse voRes = new VoResponse();
        voRes.setData(cmsExchangesService.getById(id));
        return voRes;
    }
    
    @PostMapping("enrolls/page")
    public VoResponse getExchangeEnrolls(@RequestBody(required=false) VoQueryExchanges query, @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
            @RequestParam(value="orderBy",required=false)  String orderBy) {
        VoResponse voRes = new VoResponse();
        voRes.setData(cmsExchangesService.getEnrollPageByCondition(query, pageNum, pageSize, orderBy));
        return voRes;
    }
    
    private VoResponse vaiidate(CmsExchanges e) {
        VoResponse voRes = new VoResponse();
        if(WzStrUtil.isBlank(e.getTitle())) {
            voRes.setFail(voRes);
            voRes.setMessage("活动名称必须填写");
        }
        if(WzStrUtil.isBlank(e.getSubject())) {
            voRes.setFail(voRes);
            voRes.setMessage("活动主题必须填写");
        }
        if(WzStrUtil.isBlank(e.getExAddr())) {
            voRes.setFail(voRes);
            voRes.setMessage("活动地址必须填写");
        }
        if(null == e.getEnrollStart()) {
            voRes.setFail(voRes);
            voRes.setMessage("报名开始时间必须选择");
        }
        if(null == e.getEnrollEnd()) {
            voRes.setFail(voRes);
            voRes.setMessage("报名结束时间必须选择");
        }
        if(null == e.getExStart()) {
            voRes.setFail(voRes);
            voRes.setMessage("活动开始时间必须选择");
        }
        if(null == e.getExEnd()) {
            voRes.setFail(voRes);
            voRes.setMessage("活动结束时间必须选择");
        }
        if (e.getEnrollStart().after(e.getEnrollEnd())) {
            voRes.setFail(voRes);
            voRes.setMessage("报名结束时间不能早于报名开始时间");
        }
        if (e.getExStart().after(e.getExEnd())) {
            voRes.setFail(voRes);
            voRes.setMessage("活动结束时间不能早于活动开始时间");
        }
        if (e.getEnrollStart().after(e.getExStart())) {
            voRes.setFail(voRes);
            voRes.setMessage("报名开始时间不能晚于活动开始时间");
        }
        if (e.getEnrollEnd().after(e.getExEnd())) {
            voRes.setFail(voRes);
            voRes.setMessage("报名结束时间不能晚于活动结束时间");
        }
        if(WzStrUtil.isBlank(e.getOrganizerName())) {
            voRes.setFail(voRes);
            voRes.setMessage("主办方必须填写");
        }
        if(WzStrUtil.isBlank(e.getOrgContacts())) {
            voRes.setFail(voRes);
            voRes.setMessage("主办方联系人必须填写");
        }
        if(WzStrUtil.isBlank(e.getOrgPhone())) {
            voRes.setFail(voRes);
            voRes.setMessage("联系人电话必须填写");
        }
        String[] pArr = e.getOrgPhone().split(",");
        for (String ps : pArr) {
            if (!WzStrUtil.isMobile(ps) && !WzStrUtil.isPhone(ps)) {
                voRes.setFail(voRes);
                voRes.setMessage("联系人电话格式错误，多个电话请用“,”分割");
                break;
            }
        }
        if (1 == e.getPublishNow() && null == e.getPublishDate()) {
            voRes.setFail(voRes);
            voRes.setMessage("定时发布时发布时间必须选择");
        }
        if(e.getCheckStatus()<-1 || e.getCheckStatus()>2) {
            voRes.setFail(voRes);
            voRes.setMessage("错误的活动状态");
        }
        return voRes;
    }
    
    /**
     * 保存草稿,提交待审核活动信息
     * @param e
     * @return
     */
    @PostMapping("submit")
    public VoResponse submit(@RequestBody CmsExchanges e) {
        VoResponse voRes = this.vaiidate(e);
        if(voRes.getSuccess()) {
            if(e.getCheckStatus() == 1) {
                e.setCheckStatus(0);
            }
            voRes = cmsExchangesService.saveOrUpdate(e);
        }
        return voRes;
    }
    
    /**
     * 保存草稿,提交或者直接发布活动信息
     * @param e
     * @return
     */
    @PostMapping("add")
    public VoResponse add(@RequestBody CmsExchanges e) {
        VoResponse voRes = this.vaiidate(e);
        if(voRes.getSuccess()) {
            voRes = cmsExchangesService.saveOrUpdate(e);
        }
        return voRes;
    }
    
    @DeleteMapping
    public VoResponse del(@RequestParam("id") String id) {
        VoResponse voRes = new VoResponse();
        int result = cmsExchangesService.del(id);
        voRes.setData(result);
        return voRes;
    }
    
    @PutMapping("reject")
    public Object exchangeReject(@RequestBody Map<String,String> map){
        VoResponse voRes = cmsExchangesService.reject(map.get("id"), map.get("info"));
        return voRes;
    }
    
    /**
     * 审核 批量
     * @param ids
     * @return
     */
    @PutMapping("check")
    public Object exchangeCheck(@RequestBody List<String> ids){
        VoResponse voRes = cmsExchangesService.check(ids);
        return voRes;
    }
    
    @PutMapping("on")
    public Object exchangeOn(@RequestBody List<String> ids){
        //VoResponse voRes = cmsExchangesService.onOrOff(id, 1);
        VoResponse voRes = null;
        for(String id : ids) {
            voRes = cmsExchangesService.onOrOff(id, 1);
        }
        return voRes;
    }
    
    @PutMapping("off")
    public Object exchangeOff(@RequestBody List<String> ids){
        VoResponse voRes = null;
        for(String id : ids) {
            voRes = cmsExchangesService.onOrOff(id, 0);
        }
        return voRes;
    }
    
    @PutMapping("top")
    public Object exchangeTop(@RequestParam("id") String id, @RequestParam(value = "order", required=false, defaultValue="0") Integer order){
        VoResponse voRes = cmsExchangesService.isTop(id, order);
        return voRes;
    }
    
    /**
     * 获取活动和内容的待审核数据（代办）
     * @return
     */
    @GetMapping("getSubmitCmsSum")
    public Object getSubmitLibSum(){
        return cmsExchangesService.taskDoingSum();
    }
    
    /**
     * 文件上传form
     * @param file
     * @param fileType
     * @return
     */
    @PostMapping("upload")
    public Object upload(@RequestParam("file")MultipartFile file, @RequestParam(value="fileType",defaultValue="0") String fileType) {
        MyFileUtil util = new MyFileUtil();
        String path = "exchanges/";
        String filePath = tomcatPath + path;
        
        VoResponse voRes = null;
        CmsFile e = null;
        String fileName = file.getOriginalFilename();
        if(fileType.equals("0")) {
            String [] suffixNames = {".jpg", ".jpeg", ".png", ".gif", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".txt", ".mp4"};
            voRes = util.upload(file, filePath, suffixNames);
            if(voRes.getSuccess()) {
                e = new CmsFile();
                e.setFileName(fileName);
                e.setOwnerType(1);
                e.setReqRelUrl(voRes.getData().toString());
                String sp = path + voRes.getData();
                if (WzStrUtil.isNotBlank(sp) && sp.startsWith("/")) {
                    sp = sp.substring(1);
                }
                e.setSavePath(sp);
                if(cmsFileService.add(e)) {
                    voRes.setData(e); 
                }
            }
        }else {
            String [] suffixNames = {".jpg", ".jpeg", ".png", ".gif"};
            voRes = util.upload(file, filePath, suffixNames);
            if(voRes.getSuccess()) {
                e = new CmsFile();
                e.setFileName(fileName);
                e.setOwnerType(1);
                e.setReqRelUrl(voRes.getData().toString());
                String sp = path + voRes.getData();
                if (WzStrUtil.isNotBlank(sp) && sp.startsWith("/")) {
                    sp = sp.substring(1);
                }
                e.setSavePath(sp);
                voRes.setData(e);
            }
        }
        return voRes;
    }
    
    /**
     * 文件上传base64
     * @param strfile
     * @return
     */
    @PostMapping("upload2")
    public Object upload2(@RequestBody String strfile) {
        MyFileUtil util = new MyFileUtil();
        String path = "exchanges/";
        String filePath = tomcatPath + path;
        String [] suffixNames = {".jpg", ".jpeg", ".png", ".gif", ".xls", ".xlsx", ".doc", ".docx", ".ppt", ".pptx", ".txt", ".mp4"};
        VoResponse voRes = util.upload2(strfile, filePath, suffixNames);
        return voRes;
    }

    @GetMapping("/download")
    public Object downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        MyFileUtil util = new MyFileUtil();
        String path = "exchanges/";
        String filePath = tomcatPath + path;
        VoResponse voRes = util.download(fileName, filePath, response);
        return voRes;
    }

    @GetMapping("/exportenroll")
    public Object exportEnroll(HttpServletResponse response, @RequestParam(value = "exId", required = true) String exId, @RequestParam(value = "token", required = true) String token) throws IOException {
        if (WzStrUtil.isBlank(exId)) {
            VoResponse voRes = new VoResponse();
            voRes.setFail(voRes);
            voRes.setMessage("未知的活动");
            return voRes;
        }
        if (WzStrUtil.isBlank(token)) {
            VoResponse voRes = new VoResponse();
            voRes.setFail(voRes);
            voRes.setMessage("未登录或登录已超时");
            return voRes;
        }
        String mimeType = "application/octet-stream";
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", "lib-export.xlsx");
        response.setHeader(headerKey, headerValue);
        response.setContentType(mimeType);
        VoQueryExchanges query = new VoQueryExchanges();
        query.setId(exId);
        query.setTokenStr(token);
        VoResponse voRes = cmsExchangesService.exportEnroll(query, response.getOutputStream());
        return voRes;
    }
}
